package com.jame.basics.thread.juc;

import java.util.HashSet;
import java.util.Set;

/**
 * @author : Jame
 * @date : 2021-01-10 11:47
 **/
public class ProducersAndConsumers {
    public static void main(String[] args) throws InterruptedException {
        Warehouse warehouse = new Warehouse();
        Producers producers = new Producers(warehouse);
        Consumers consumers = new Consumers(warehouse);
        Thread p = new Thread(producers, "生产者");
        Thread c = new Thread(consumers, "消费者");
        p.start();
        c.start();


    }
}

class Producers implements Runnable {
    private Warehouse warehouse;

    public Producers(Warehouse warehouse) {
        this.warehouse = warehouse;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            warehouse.pushApples(new Apple());
            System.out.println("生产了第" + i + "个苹果");
        }
    }
}

class Consumers implements Runnable {
    private Warehouse warehouse;
    int i = 0;

    public Consumers(Warehouse warehouse) {
        this.warehouse = warehouse;
    }

    @Override
    public void run() {
        while (true) {
            Set<Apple> apples = warehouse.getApples();
            System.out.println("===========" + apples.size());
            for (Apple apple : apples) {
                System.out.println("消费了第:" + (++i) + "个苹果");
                if (i == 100) {
                    break;
                }
            }
            apples.clear();
            if (i == 100)
                break;
        }
    }
}

//缓冲区,仓库
class Warehouse {
    //存储苹果
    Set<Apple> apples = new HashSet<>();

    //生产者放入苹果方法,最多放30个,超过30个等待
    public synchronized void pushApples(Apple apple) {
        while (apples.size() == 30) {
            try {
                this.wait(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.apples.add(apple);

    }

    public  Set<Apple> getApples() {
        while (apples.isEmpty()) {
            try {
                this.wait(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        HashSet<Apple> RApples = new HashSet<>();
        RApples.addAll(apples);
        apples.clear();
        return RApples;
    }
}

class Apple {

}

